//
//  XZChatViewController.m
//  XZ_WeChat
//
//  Created by 曹宗华  on 16/9/27.
//  Copyright © 2016年 gxz. All rights reserved.
//

#import "XZChatViewController.h"
#import "ICChatHearder.h"
#import "AccountVerifyController.h"
#import "SocketRocketUtility.h"
#import <WebKit/WebKit.h>
 //  http://172.16.1.174:9901/yichat/broker
@interface XZChatViewController ()<ICChatBoxViewControllerDelegate,UITableViewDelegate,UITableViewDataSource,ICRecordManagerDelegate,UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning,BaseCellDelegate,VerifyCellDelegate,messageLinkDelegate,receiveMessageDelegate>
{
    CGRect _smallRect;
    CGRect _bigRect;
    
    UIMenuItem * _copyMenuItem;
    UIMenuItem * _deleteMenuItem;
    UIMenuItem * _forwardMenuItem;
    UIMenuItem * _recallMenuItem;
    NSIndexPath *_longIndexPath;
    
    BOOL   _isKeyBoardAppear;     // 键盘是否弹出来了
    int   loadCount;
    int  remainder;
}

@property (nonatomic, strong) ICChatBoxViewController *chatBoxVC;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITextView *textView;
/** 数据源 */
@property (nonatomic, strong) NSMutableArray *dataSource;
/** voice path */
@property (nonatomic, copy) NSString *voicePath;

@property (nonatomic, strong) UIViewController* videoVc;

@property (nonatomic, strong) UIImageView *currentVoiceIcon;
@property (nonatomic, strong) UIImageView *presentImageView;
@property (nonatomic, assign)  BOOL presentFlag;  // 是否model出控制器
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) ICVoiceHud *voiceHud;
@property(nonatomic,strong)HttpRequest *request;
@property(nonatomic,strong)HttpRequestWithToken *request2;
@property(nonatomic,strong)NSString *urlHead;
@property(nonatomic,strong)NSString *username;
@property(nonatomic,strong)NSString *token;
@property(nonatomic,strong)NSString *userId;
@property(nonatomic,strong)NSString *sessionId;
@property(nonatomic,strong)UIButton *transferBtn;//转人工按钮
@property(nonatomic,strong)UIButton *deleteBtn;//删除按钮
@property(nonatomic)BOOL   firstClicked;
@property(nonatomic,strong)NSString *messageTime;
@property(nonatomic,strong)UIRefreshControl *refrenshControl;
@property(nonatomic,strong)NSMutableArray *tempDataAry;
@property(nonatomic,strong)NSArray *subAry;
@property(nonatomic,strong)NSString *custAcctType;
@property(nonatomic,strong)NSString *msgFrom;
@property(nonatomic)BOOL IsCustermerOnline;
@property(nonatomic,strong)NSMutableArray *notifyAry;
@property(nonatomic,strong)NSString *currentNotifyID;
@end

@implementation XZChatViewController
- (id)init
{
    self=[super init];
    if (self) {
        self.request=[[HttpRequest alloc] init];
        self.request2=[[HttpRequestWithToken alloc] init];
        self.firstClicked=NO;
        self.IsCustermerOnline=NO;//初始化客服不在线
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = self.group.gName;
    
    [self setupUI];
    
    [self registerCell];
    
    [self loadDataSource];
    [[YiChatClient shareInstance] detectSensitiveWords:@"妈的" Success:^(NSString *info) {
        NSLog(@"敏感词检测:%@",info);
    } fail:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}
- (NSMutableArray*)notifyAry
{
    if(!_notifyAry)
    {
        _notifyAry=[[NSMutableArray alloc] init];
    }
    return _notifyAry;
}
-(UIRefreshControl*)refrenshControl
{
    if (!_refrenshControl) {
        _refrenshControl=[[UIRefreshControl alloc] init];
        [_refrenshControl addTarget:self action:@selector(refreshHistory) forControlEvents:UIControlEventValueChanged];
        [self.tableView addSubview:_refrenshControl];
    }
    return _refrenshControl;
}
- (void)setupUI
{
//    UIButton *backBtn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
//    UIButton *backBtn=[[UIButton alloc] init];
//    backBtn.frame=CGRectMake(0, 0, 40, 20);
//    [backBtn.widthAnchor constraintEqualToConstant:15].active=YES;
//    [backBtn.heightAnchor constraintEqualToConstant:20].active=YES;
//    [backBtn setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
////    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
//    backBtn.contentMode=UIViewContentModeScaleToFill;
//    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
//    [navView addSubview:backView];
    
    UIImageView *btnImageView=[[UIImageView alloc] initWithFrame:CGRectMake(10, 0, 10, 20)];
    btnImageView.image=[UIImage imageNamed:@"返回"];
    btnImageView.userInteractionEnabled=YES;
    [backView addSubview:btnImageView];
    
    UIControl *control = [[UIControl alloc] initWithFrame:backView.bounds];
    [control addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:control];
    
    UIBarButtonItem *backItem=[[UIBarButtonItem alloc] initWithCustomView:backView];
    self.navigationItem.leftBarButtonItem=backItem;
//    self.navigationItem.backBarButtonItem=backItem;
     [self.navigationController.navigationBar setBarTintColor:XZColor(50, 164,238)];
    self.view.backgroundColor = IColor(240, 237, 237);
    // 注意添加顺序
    [self addChildViewController:self.chatBoxVC];
    [self.view addSubview:self.chatBoxVC.view];
    [self.view addSubview:self.tableView];
    
    self.tableView.backgroundColor = IColor(240, 237, 237);
    // self.view的高度有时候是不准确的
    self.tableView.frame = CGRectMake(0, HEIGHT_NAVBAR+HEIGHT_STATUSBAR, self.view.width, APP_Frame_Height-HEIGHT_TABBAR-HEIGHT_NAVBAR-HEIGHT_STATUSBAR);
    self.transferBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    self.transferBtn.frame=CGRectMake(0, 0, 60, 30);
    self.transferBtn.layer.cornerRadius=5;
    self.transferBtn.clipsToBounds=YES;
    [self.transferBtn setTitle:@"转人工" forState:UIControlStateNormal];
    self.transferBtn.backgroundColor=[UIColor yellowColor];
    [self.transferBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.transferBtn addTarget:self action:@selector(transferToAgent) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightItem=[[UIBarButtonItem alloc] initWithCustomView:_transferBtn];
//    self.navigationItem.rightBarButtonItem=rightItem;
    self.deleteBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    self.deleteBtn.frame=CGRectMake(0, 0, 30, 30);
    self.deleteBtn.layer.cornerRadius=5;
    self.deleteBtn.clipsToBounds=YES;
    [self.deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
    self.deleteBtn.backgroundColor=[UIColor greenColor];
    [self.deleteBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.deleteBtn addTarget:self action:@selector(deleteLocalDB) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem2=[[UIBarButtonItem alloc] initWithCustomView:_deleteBtn];
    self.navigationItem.rightBarButtonItems=@[rightItem,rightItem2];
//    self.navigationItem.rightBarButtonItems
    self.refrenshControl.backgroundColor=[UIColor grayColor];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    NSString *username=@"zonghua2";
    NSString *password=@"123456";
    NSString *niceName=@"subhua";
    if([[NSUserDefaults standardUserDefaults] objectForKey:@"userName"]!=nil)
    {
        username=[[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
        password=[[NSUserDefaults standardUserDefaults] objectForKey:@"passWord"];
        niceName= [[NSUserDefaults standardUserDefaults] objectForKey:@"nickName"];
    }
  
    NSLog(@"用户信息:%@,%@,%@",username,password,niceName);
    self.username=username;
    [[NSUserDefaults standardUserDefaults] setObject:username forKey:@"username"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    NSDictionary *userinfo=@{@"username":username,@"password":password,@"niceName":niceName};
     [[YiChatClient shareInstance] addVisitorUserinfo:userinfo Success:^(NSString *info) {
         NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
         NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
         NSLog(@"增加用户结果:%@",returnDic);
         if([returnDic[@"response"][@"resultCode"] intValue]==0)
         {
             NSLog(@"增加用户成功");
             [self visitorLogin];
             
         }else if ([returnDic[@"response"][@"resultCode"] intValue]==100030)
         {
              NSLog(@"用户名已存在");
             [self visitorLogin];
         }else if ([returnDic[@"response"][@"resultCode"] intValue]==100002)
         {
              NSLog(@"参数错误");
         }
    } fail:^(NSError *error) {
        
    }];
/**
    if(![[NSUserDefaults standardUserDefaults] objectForKey:@"username"])
    {
         NSLog(@"第一登录，需获取临时访客用户名");
        [[YiChatClient shareInstance] getVisitorNameSuccess:^(NSString *info) {
            self.username=info;
            [self visitorLogin];
           
        } fail:^(NSError *error) {
            NSLog(@"获取用户名报错:%@",error.localizedDescription);
        }];
    }else
    {
        NSLog(@"用户名已经存在，直接登录");
        self.username=[[NSUserDefaults standardUserDefaults] objectForKey:@"username"];
          [self visitorLogin];
    }
 */
//    self.tabBarController.hidesBottomBarWhenPushed=YES;
}
- (void)backClick
{
//    [[YiChatClient shareInstance] dropSession];
//    [[YiChatClient shareInstance] dropSession:self.sessionId Success:^(NSString *info) {
//        NSLog(@"dropSession:%@",info);
//
//
//    }];
    [[SocketRocketUtility instance] SRWebSocketClose];
    [[YiChatClient shareInstance] getLatestSessionSuccess:^(NSString *info) {
        if(info==nil)
        {
            NSLog(@"获取会话返回空");
        }
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"获取最新会话:%@",returnDic);
        
    } fail:^(NSError *error) {
        NSLog(@"获取最新会话报错:%@",error.localizedDescription);
    }];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    if ([SocketRocketUtility instance].socketReadyState==SR_OPEN) {
         [[SocketRocketUtility instance] SRWebSocketClose];//关闭socket连接
    }
}
- (void)refreshHistory
{
    NSLog(@"下拉刷新了");
//    [self loadDataSource];
//    if (([self.tempDataAry count]-loadCount*10)>10) {
//        self.subAry=[self.tempDataAry subarrayWithRange:NSMakeRange(loadCount*10, 10)];
//        for (ICMessageFrame *messageF in  self.subAry) {
//            [self addObject:messageF isSender:NO];
//            [self messageSendSucced:messageF];
//        }
//        loadCount++;
//
//    }else if (([self.tempDataAry count]-loadCount*10)<=remainder)
//    {
//        self.subAry=[self.tempDataAry subarrayWithRange:NSMakeRange(loadCount*10, remainder)];
//        for (ICMessageFrame *messageF in  self.subAry) {
//            [self addObject:messageF isSender:NO];
//            [self messageSendSucced:messageF];
//        }
//        loadCount++;
//    }else if ([self.tempDataAry count]<loadCount*10)
//    {
//        NSLog(@"本地数据已全部加载");
//    }
    
    [self.refrenshControl endRefreshing];
}
- (NSMutableArray*)tempDataAry
{
    if(!_tempDataAry)
    {
        _tempDataAry=[[NSMutableArray alloc] init];
    }
    return _tempDataAry;
}
- (NSArray*)subAry
{
    if (!_subAry) {
        _subAry=[[NSArray alloc] init];
    }
    return _subAry;
}
- (void)registerCell
{
    [self.tableView registerClass:[ICChatMessageTextCell class] forCellReuseIdentifier:TypeText];
    [self.tableView registerClass:[ICChatMessageImageCell class] forCellReuseIdentifier:TypePic];
    [self.tableView registerClass:[ICChatMessageVideoCell class] forCellReuseIdentifier:TypeVideo];
    [self.tableView registerClass:[ICChatMessageVoiceCell class] forCellReuseIdentifier:TypeVoice];
    [self.tableView registerClass:[ICChatMessageFileCell class] forCellReuseIdentifier:TypeFile];
    [self.tableView registerClass:[ICChatMessageVerifyCell class] forCellReuseIdentifier:TypeVerify];
}

// 加载数据
- (void)loadDataSource
{
//    [weadSelf.dataSource addObjectsFromArray:array];
//    [weadSelf scrollToBottom];

    if([[NSUserDefaults standardUserDefaults] objectForKey:@"username"]!=nil)
    {
        NSArray *objectAry=[[MessageManager shareInstance] queryFromDB];
        if (objectAry) {
            for (NSManagedObject *object in objectAry) {
                NSString *path= [object valueForKey:@"path"];
                NSString *from=[object valueForKey:@"from"];
                NSString *to=[object valueForKey:@"to"];
                NSString *type=[object valueForKey:@"type"];
                BOOL  isSender=[[object valueForKey:@"isSender"] boolValue];
                NSDate *date=[object valueForKey:@"date"];
                NSString *content=[object valueForKey:@"content"];
                MessageDeliveryState  deliveryState=[[object valueForKey:@"deliveryState"] intValue];
                ICMessageFrame *messageF=[ICMessageHelper createMessageFrame:type content:content path:path from:from to:to fileKey:nil isSender:isSender receivedSenderByYourself:NO];
                messageF.model.message.deliveryState=deliveryState;
//                NSLog(@"deliveryState:%d",deliveryState);
                [self addObject:messageF isSender:isSender];
                [self messageSendSucced:messageF];
                
                
            }
        }
    }
   
}

#pragma mark - Tableview data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id obj                            = self.dataSource[indexPath.row];
    if ([obj isKindOfClass:[NSString class]]) {
        return nil;
    } else {
        ICMessageFrame *modelFrame     = (ICMessageFrame *)obj;
        NSString *ID                   = modelFrame.model.message.type;
        if ([ID isEqualToString:TypeSystem]) {
            ICChatSystemCell *cell = [ICChatSystemCell cellWithTableView:tableView reusableId:ID];
            cell.messageF              = modelFrame;
            return cell;
        }
        if([ID isEqualToString:TypeText])
        {
            ICChatMessageTextCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
            cell.modelFrame               = modelFrame;
            cell.delegate=self;
            if(cell.modelFrame.model.isSender)
            {
                cell.headImageView.imageView.image=[UIImage imageNamed:@"sender.png"];
            }else
            {
                if([cell.modelFrame.model.message.from isEqualToString:@"10001"])
                {
                    [cell.headImageView.imageView  setImage:[UIImage imageNamed:@"jiqiren_03.png"]];
                }else
                {
                    [cell.headImageView.imageView  setImage:[UIImage imageNamed:@"seatService.png"]];
                }
            }
            return cell;
        }
        if([ID isEqualToString:TypeVerify])
        {
            ICChatMessageVerifyCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
            cell.longPressDelegate =self;
            cell.verifydelegate=self;
//            NSLog(@"委托代理");
            
            [[ICMediaManager sharedManager] clearReuseImageMessage:cell.modelFrame.model];
            cell.modelFrame                = modelFrame;
            if(cell.modelFrame.model.isSender)
            {
                cell.headImageView.imageView.image=[UIImage imageNamed:@"sender.png"];
            }else
            {

                [cell.headImageView.imageView  setImage:[UIImage imageNamed:@"seatService.png"]];
            }
            return cell;
        }
            ICChatMessageBaseCell *cell    = [tableView dequeueReusableCellWithIdentifier:ID];
            cell.longPressDelegate         = self;
        
        
        
        [[ICMediaManager sharedManager] clearReuseImageMessage:cell.modelFrame.model];
        cell.modelFrame                = modelFrame;
        if(cell.modelFrame.model.isSender)
        {
            cell.headImageView.imageView.image=[UIImage imageNamed:@"sender.png"];
        }else
        {
            if([cell.modelFrame.model.message.from isEqualToString:@"10001"])
            {
                 [cell.headImageView.imageView  setImage:[UIImage imageNamed:@"jiqiren_03.png"]];
            }else
            {
                 [cell.headImageView.imageView  setImage:[UIImage imageNamed:@"seatService.png"]];
            }
        }
        return cell;
    }
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ICMessageFrame *messageF = [self.dataSource objectAtIndex:indexPath.row];
    return messageF.cellHight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.chatBoxVC resignFirstResponder];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.chatBoxVC resignFirstResponder];
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)indexPath {
    if ([cell isKindOfClass:[ICChatMessageVideoCell class]] && self) {
        ICChatMessageVideoCell *videoCell = (ICChatMessageVideoCell *)cell;
        [videoCell stopVideo];
    }
}

#pragma mark - ICChatBoxViewControllerDelegate

- (void) chatBoxViewController:(ICChatBoxViewController *)chatboxViewController
        didChangeChatBoxHeight:(CGFloat)height
{
    self.chatBoxVC.view.top = self.view.bottom-height;
    self.tableView.height = HEIGHT_SCREEN - height - HEIGHT_NAVBAR-HEIGHT_STATUSBAR;
    if (height == HEIGHT_TABBAR) {
        [self.tableView reloadData];
        _isKeyBoardAppear  = NO;
    } else {
        [self scrollToBottom];
        _isKeyBoardAppear  = YES;
    }
    if (self.textView == nil) {
        self.textView = chatboxViewController.chatBox.textView;
    }
}

- (void)chatBoxViewController:(ICChatBoxViewController *)chatboxViewController didVideoViewAppeared:(ICVideoView *)videoView
{
    [_chatBoxVC.view setFrame:CGRectMake(0, HEIGHT_SCREEN-HEIGHT_TABBAR, App_Frame_Width, APP_Frame_Height)];
    videoView.hidden = NO;
    [UIView animateWithDuration:0.5 animations:^{
        self.tableView.height = HEIGHT_SCREEN - videwViewH - HEIGHT_NAVBAR-HEIGHT_STATUSBAR;
        self.chatBoxVC.view.frame = CGRectMake(0, videwViewX+HEIGHT_NAVBAR+HEIGHT_STATUSBAR, App_Frame_Width, videwViewH);
        [self scrollToBottom];
    } completion:^(BOOL finished) { // 状态改变
        self.chatBoxVC.chatBox.status = ICChatBoxStatusShowVideo;
        // 在这里创建视频设配
        UIView *videoLayerView = [videoView viewWithTag:1000];
        UIView *placeholderView = [videoView viewWithTag:1001];
        [[ICVideoManager shareManager] setVideoPreviewLayer:videoLayerView];
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(videoPreviewLayerWillAppear:) userInfo:placeholderView repeats:NO];
        
    }];
}

- (void)chatBoxViewController:(ICChatBoxViewController *)chatboxViewController sendVideoMessage:(NSString *)videoPath
{
    ICMessageFrame *messageFrame = [ICMessageHelper createMessageFrame:TypeVideo content:@"[视频]" path:videoPath from:@"gxz" to:self.group.gId fileKey:nil isSender:YES receivedSenderByYourself:NO]; // 创建本地消息
    [self addObject:messageFrame isSender:YES];
    [self messageSendSucced:messageFrame];
}

- (void) chatBoxViewController:(ICChatBoxViewController *)chatboxViewController sendFileMessage:(NSString *)fileName
{
    NSString *lastName = [fileName originName];
    NSString*fileKey   = [fileName firstStringSeparatedByString:@"_"];
    NSString *content = [NSString stringWithFormat:@"[文件]%@",lastName];
    ICMessageFrame *messageFrame = [ICMessageHelper createMessageFrame:TypeFile content:content path:fileName from:@"gxz" to:self.group.gId fileKey:nil isSender:YES receivedSenderByYourself:NO];
    NSString *path = [[ICFileTool fileMainPath] stringByAppendingPathComponent:fileName];
    double s = [ICFileTool fileSizeWithPath:path];
    NSNumber *x = [ICMessageHelper fileType:[fileName pathExtension]];
    if (!x) {
        x = @0;
    }
    NSDictionary *lnk = @{@"s":@((long)s),@"x":x,@"n":lastName};
    messageFrame.model.message.lnk = [lnk jsonString];
    messageFrame.model.message.fileKey = fileKey;
    [self addObject:messageFrame isSender:YES];
    [self messageSendSucced:messageFrame];
}

// send text message
- (void) chatBoxViewController:(ICChatBoxViewController *)chatboxViewController
               sendTextMessage:(NSString *)messageStr
{
    if (messageStr && messageStr.length > 0) {
//         [self sendMessage:messageStr];
//        [self sendMessage:messageStr type:@"text"];
        if(self.IsCustermerOnline==NO) //客服不在线，转人工
        {
            if([messageStr rangeOfString:@"转人工"].location!=NSNotFound)
            {
                [[YiChatClient shareInstance] transferToAgent];
                NSLog(@"转人工");
            }
        }
        
      
             [[YiChatClient shareInstance] sendMessage:messageStr type:@"text"];
             NSLog(@"发送消息:%@",messageStr);
        
       
       
        [self sendTextMessageWithContent:messageStr];
        
//       [self otherSendTextMessageWithContent:messageStr];
    }
}

- (void)sendTextMessageWithContent:(NSString *)messageStr
{
     [self sendSystemMessage:[NFTool getCurrentDate]];//发送时间消息
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypeText content:messageStr path:nil from:@"gxz" to:self.group.gId fileKey:nil isSender:YES receivedSenderByYourself:NO];
    
     [self saveMessageToDB:messageF];
    [self addObject:messageF isSender:YES];
    [self messageSendSucced:messageF];
    
   
}

//- (void)otherSendTextMessageWithContent:(NSString *)messageStr
- (void)otherSendTextMessageWithContent:(NSString *)messageStr msgFrom:(NSString*)from
{
    [self sendSystemMessage:[NFTool getCurrentDate]];//发送时间消息
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypeText content:messageStr path:nil from:from to:self.group.gId fileKey:nil isSender:NO receivedSenderByYourself:NO];
    [self addObject:messageF isSender:YES];
    [self saveMessageToDB:messageF];
    [self messageSendSucced:messageF];
}
-  (void)sendSystemMessage:(NSString*)content
{
    ICMessageFrame *messageS=[ICMessageHelper createMessageFrame:TypeSystem content:content path:nil from:@"gxz" to:self.group.gId fileKey:nil isSender:YES receivedSenderByYourself:NO];
//    [self saveMessageToDB:messageS];
    [self addObject:messageS isSender:YES];
    [self messageSendSucced:messageS];
}

// 增加数据源并刷新
- (void)addObject:(ICMessageFrame *)messageF
         isSender:(BOOL)isSender
{
    [self.dataSource addObject:messageF];
    [self.tableView reloadData];
    if (isSender || _isKeyBoardAppear) {
        [self scrollToBottom];
    }
}
/*
 *功能：存储消息到本地
 *
 */
- (void)saveMessageToDB:(ICMessageFrame*)messageS
{
    [[MessageManager shareInstance] createMessageObject:messageS];
    NSError *error=nil;
    [[MessageManager shareInstance].context save:&error];
}
- (void)messageSendSucced:(ICMessageFrame *)messageF
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        messageF.model.message.deliveryState = ICMessageDeliveryState_Delivered;
        [self.tableView reloadData];
    });
}


// send image message
- (void) chatBoxViewController:(ICChatBoxViewController *)chatboxViewController
              sendImageMessage:(UIImage *)image
                     imagePath:(NSString *)imgPath
{
    if (image && imgPath) {
        NSLog(@"imgPath:%@",imgPath);
        NSData *imageData=[self imageToData:image];
//          [self uploadFile:imageData type:@"image"];
        [[YiChatClient shareInstance] uploadFile:imageData type:@"image"];
//       [self uploadFile:image];
         [self sendSystemMessage:[NFTool getCurrentDate]];//发送时间消息
        [self sendImageMessageWithImgPath:imgPath];
    }
}

- (void)sendImageMessageWithImgPath:(NSString *)imgPath
{
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypePic content:@"[图片]" path:imgPath from:@"gxz" to:self.group.gId fileKey:nil isSender:YES receivedSenderByYourself:NO];
    [self addObject:messageF isSender:YES];
     [self saveMessageToDB:messageF];
    [self messageSendSucced:messageF];
    
}
- (void)otherSendImageMessageWithImgPath:(NSString *)imgPath
{
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypePic content:@"[图片]" path:imgPath from:@"zuoxi" to:self.group.gId fileKey:nil isSender:NO receivedSenderByYourself:NO];
     [self saveMessageToDB:messageF];
    [self addObject:messageF isSender:YES];
    
    [self messageSendSucced:messageF];
    
}
- (void)otherSendVerifyMessage:(NSString*)message
{
    ICMessageFrame *messageS=[ICMessageHelper createMessageFrame:TypeVerify content:message path:nil from:@"zuoxi" to:self.group.gId fileKey:nil isSender:NO receivedSenderByYourself:NO];
     [self saveMessageToDB:messageS];
    [self addObject:messageS isSender:YES];
    [self messageSendSucced:messageS];
}
// send voice message
- (void) chatBoxViewController:(ICChatBoxViewController *)chatboxViewController sendVoiceMessage:(NSString *)voicePath
{
    [self timerInvalue]; // 销毁定时器
    self.voiceHud.hidden = YES;
    if (voicePath) {
        NSData *voiceData=[NSData dataWithContentsOfFile:voicePath];
//        NSLog(@"voiceData:%ld",voiceData.length);
        NSLog(@"voicePath:%@",voicePath);
        
//        NSString *voicePath = [self mediaPath:modelFrame.model.mediaPath];
      NSString *voiceTime  = [NSString stringWithFormat:@"%d''",[[ICRecordManager shareManager] durationWithVideo:[NSURL fileURLWithPath:voicePath]]];
        NSLog(@"voiceTime:%@",voiceTime);
        [YiChatClient shareInstance].voiceLength=voiceTime;
//        [self uploadFile:voiceData type:@"voice"];
        [[YiChatClient shareInstance] uploadFile:voiceData type:@"voice"];
         [self sendSystemMessage:[NFTool getCurrentDate]];//发送时间消息
        ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypeVoice content:@"[语音]" path:voicePath from:@"gxz" to:self.group.gId fileKey:nil isSender:YES receivedSenderByYourself:NO];
         [self saveMessageToDB:messageF];
        [self addObject:messageF isSender:YES];
        [self messageSendSucced:messageF];
    }
}
- (void)otherSendVoiceMessage:(NSString*)path
{
    if(path)
    {
        NSData *voiceData=[NSData dataWithContentsOfFile:path];
         NSLog(@"voiceData:%ld",voiceData.length);
    }
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypeVoice content:@"[语音]" path:path from:@"zuoxi" to:self.group.gId fileKey:nil isSender:NO receivedSenderByYourself:NO];
     [self saveMessageToDB:messageF];
    [self addObject:messageF isSender:YES];
    [self messageSendSucced:messageF];
}

#pragma mark - baseCell delegate

- (void)longPress:(UILongPressGestureRecognizer *)longRecognizer
{
    if (longRecognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint location       = [longRecognizer locationInView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
        _longIndexPath         = indexPath;
        id object              = [self.dataSource objectAtIndex:indexPath.row];
        if (![object isKindOfClass:[ICMessageFrame class]]) return;
        ICChatMessageBaseCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        [self showMenuViewController:cell.bubbleView andIndexPath:indexPath message:cell.modelFrame.model];
    }
}
#pragma mark - VerifyCellDelegate
- (void)popVerifvc
{
    NSLog(@"弹出一个资金验证窗口");
//    if (!_firstClicked) {
        AccountVerifyController *vc=[[AccountVerifyController alloc] init];
        vc.custAcctType=self.custAcctType;
        [self.navigationController pushViewController:vc animated:YES];
        _firstClicked=!_firstClicked;
//    }
}
- (void)tapPopVC
{
    NSLog(@"点击手势弹出一个资金验证窗口");
    AccountVerifyController *vc=[[AccountVerifyController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - messageLinkDelegate
- (void)presentEvaluateVC:(id)cell
{
//    LeaveMessageViewController *vc=[[LeaveMessageViewController alloc] init];
//   XZNavigationController *nav=[[XZNavigationController alloc] initWithRootViewController:vc];
//    [self presentViewController:nav animated:NO completion:nil];
    EvaluateServiceViewController *vc=[[EvaluateServiceViewController alloc] init];
    vc.transferId=[YiChatClient shareInstance].transferId;
      self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
//    self.hidesBottomBarWhenPushed=YES;
}
#pragma mark - public method

// 路由响应
- (void)routerEventWithName:(NSString *)eventName
                   userInfo:(NSDictionary *)userInfo
{
    ICMessageFrame *modelFrame = [userInfo objectForKey:MessageKey];
    if ([eventName isEqualToString:GXRouterEventTextUrlTapEventName]) {
    } else if ([eventName isEqualToString:GXRouterEventImageTapEventName]) {
        _smallRect             = [[userInfo objectForKey:@"smallRect"] CGRectValue];
        _bigRect               =  [[userInfo objectForKey:@"bigRect"] CGRectValue];
        NSString *imgPath      = modelFrame.model.mediaPath;
        NSString *orgImgPath = [[ICMediaManager sharedManager] originImgPath:modelFrame];
        if ([ICFileTool fileExistsAtPath:orgImgPath]) {
            modelFrame.model.mediaPath = orgImgPath;
            imgPath                    = orgImgPath;
        }
        [self showLargeImageWithPath:imgPath withMessageF:modelFrame];
    } else if ([eventName isEqualToString:GXRouterEventVoiceTapEventName]) {
        
        UIImageView *imageView = (UIImageView *)userInfo[VoiceIcon];
        UIView *redView        = (UIView *)userInfo[RedView];
        [self chatVoiceTaped:modelFrame voiceIcon:imageView redView:redView];
    }
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

#pragma mark - voice & video

- (void)voiceDidCancelRecording
{
    [self timerInvalue];
    self.voiceHud.hidden = YES;
}
- (void)voiceDidStartRecording
{
    [self timerInvalue];
    self.voiceHud.hidden = NO;
    [self timer];
}

// 向外或向里移动
- (void)voiceWillDragout:(BOOL)inside
{
    if (inside) {
        [_timer setFireDate:[NSDate distantPast]];
        _voiceHud.image  = [UIImage imageNamed:@"voice_1"];
    } else {
        [_timer setFireDate:[NSDate distantFuture]];
        self.voiceHud.animationImages  = nil;
        self.voiceHud.image = [UIImage imageNamed:@"cancelVoice"];
    }
}
- (void)progressChange
{
    AVAudioRecorder *recorder = [[ICRecordManager shareManager] recorder] ;
    [recorder updateMeters];
    float power= [recorder averagePowerForChannel:0];//取得第一个通道的音频，注意音频强度范围时-160到0,声音越大power绝对值越小
    CGFloat progress = (1.0/160)*(power + 160);
    self.voiceHud.progress = progress;
}

- (void)voiceRecordSoShort
{
    [self timerInvalue];
    self.voiceHud.animationImages = nil;
    self.voiceHud.image = [UIImage imageNamed:@"voiceShort"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.voiceHud.hidden = YES;
    });
}

// play voice
- (void)chatVoiceTaped:(ICMessageFrame *)messageFrame
             voiceIcon:(UIImageView *)voiceIcon
               redView:(UIView *)redView
{
    ICRecordManager *recordManager = [ICRecordManager shareManager];
    recordManager.playDelegate = self;
    // 文件路径
    NSString *voicePath = [self mediaPath:messageFrame.model.mediaPath];
    NSString *amrPath   = [[voicePath stringByDeletingPathExtension] stringByAppendingPathExtension:@"amr"];
    //[VoiceConverter ConvertAmrToWav:amrPath wavSavePath:voicePath];
    if (messageFrame.model.message.status == 0){
        messageFrame.model.message.status = 1;
        redView.hidden = YES;
    }
    if (self.voicePath) {
        if ([self.voicePath isEqualToString:voicePath]) { // the same recoder
            self.voicePath = nil;
            [[ICRecordManager shareManager] stopPlayRecorder:voicePath];
            [voiceIcon stopAnimating];
            self.currentVoiceIcon = nil;
            return;
        } else {
            [self.currentVoiceIcon stopAnimating];
            self.currentVoiceIcon = nil;
        }
    }
    [[ICRecordManager shareManager] startPlayRecorder:voicePath];
    [voiceIcon startAnimating];
    self.voicePath = voicePath;
    self.currentVoiceIcon = voiceIcon;
}

// 移除录视频时的占位图片
- (void)videoPreviewLayerWillAppear:(NSTimer *)timer
{
    UIView *placeholderView = (UIView *)[timer userInfo];
    [placeholderView removeFromSuperview];
}


#pragma mark - ICRecordManagerDelegate

- (void)voiceDidPlayFinished
{
    self.voicePath = nil;
    ICRecordManager *manager = [ICRecordManager shareManager];
    manager.playDelegate = nil;
    [self.currentVoiceIcon stopAnimating];
    self.currentVoiceIcon = nil;
}

#pragma mark - UIViewControllerTransitioningDelegate

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    self.presentFlag = YES;
    return self;
}
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    self.presentFlag = NO;
    return self;
}

#pragma mark - UIViewControllerAnimatedTransitioning

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    return 0.5;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    if (self.presentFlag) {
        UIView *toView              = [transitionContext viewForKey:UITransitionContextToViewKey];
        self.presentImageView.frame = _smallRect;
        [[transitionContext containerView] addSubview:self.presentImageView];
        [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
            self.presentImageView.frame = _bigRect;
        } completion:^(BOOL finished) {
            if (finished) {
                [self.presentImageView removeFromSuperview];
                [[transitionContext containerView] addSubview:toView];
                [transitionContext completeTransition:YES];
            }
        }];
    } else {
        ICPhotoBrowserController *photoVC = (ICPhotoBrowserController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
        UIImageView *iv     = photoVC.imageView;
        UIView *fromView    = [transitionContext viewForKey:UITransitionContextFromViewKey];
        iv.center = fromView.center;
        [fromView removeFromSuperview];
        [[transitionContext containerView] addSubview:iv];
        [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
            iv.frame = _smallRect;
        } completion:^(BOOL finished) {
            if (finished) {
                [iv removeFromSuperview];
                [transitionContext completeTransition:YES];
            }
        }];
    }
}




#pragma mark - private

- (void) scrollToBottom
{
    if (self.dataSource.count > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataSource.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

// tap image
- (void)showLargeImageWithPath:(NSString *)imgPath
                  withMessageF:(ICMessageFrame *)messageF
{
    UIImage *image = [[ICMediaManager sharedManager] imageWithLocalPath:imgPath];
    if (image == nil) {
        ICLog(@"image is not existed");
        return;
    }
    ICPhotoBrowserController *photoVC = [[ICPhotoBrowserController alloc] initWithImage:image];
    self.presentImageView.image       = image;
    photoVC.transitioningDelegate     = self;
    photoVC.modalPresentationStyle    = UIModalPresentationCustom;
    [self presentViewController:photoVC animated:YES completion:nil];
}

- (void)timerInvalue
{
    [_timer invalidate];
    _timer  = nil;
}

// 文件路径
- (NSString *)mediaPath:(NSString *)originPath
{
    // 这里文件路径重新给，根据文件名字来拼接
    NSString *name = [[originPath lastPathComponent] stringByDeletingPathExtension];
    return [[ICRecordManager shareManager] receiveVoicePathWithFileKey:name];
}

- (void)showMenuViewController:(UIView *)showInView andIndexPath:(NSIndexPath *)indexPath message:(ICMessageModel *)messageModel
{
    if (_copyMenuItem   == nil) {
        _copyMenuItem   = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyMessage:)];
    }
    if (_deleteMenuItem == nil) {
        _deleteMenuItem = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(deleteMessage:)];
    }
    if (_forwardMenuItem == nil) {
        _forwardMenuItem = [[UIMenuItem alloc] initWithTitle:@"转发" action:@selector(forwardMessage:)];
    }
    NSInteger currentTime = [ICMessageHelper currentMessageTime];
    NSInteger interval    = currentTime - messageModel.message.date;
    if (messageModel.isSender) {
        if ((interval/1000) < 5*60 && !(messageModel.message.deliveryState == ICMessageDeliveryState_Failure)) {
            if (_recallMenuItem == nil) {
                _recallMenuItem = [[UIMenuItem alloc] initWithTitle:@"撤回" action:@selector(recallMessage:)];
            }
            [[UIMenuController sharedMenuController] setMenuItems:@[_copyMenuItem,_deleteMenuItem,_recallMenuItem,_forwardMenuItem]];
        } else {
            [[UIMenuController sharedMenuController] setMenuItems:@[_copyMenuItem,_deleteMenuItem,_forwardMenuItem]];
        }
    } else {
        [[UIMenuController sharedMenuController] setMenuItems:@[_copyMenuItem,_deleteMenuItem,_forwardMenuItem]];
    }
    [[UIMenuController sharedMenuController] setTargetRect:showInView.frame inView:showInView.superview ];
    [[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
}

- (void)copyMessage:(UIMenuItem *)copyMenuItem
{
    UIPasteboard *pasteboard  = [UIPasteboard generalPasteboard];
    ICMessageFrame * messageF = [self.dataSource objectAtIndex:_longIndexPath.row];
    pasteboard.string         = messageF.model.message.content;
}

- (void)deleteMessage:(UIMenuItem *)deleteMenuItem
{
    // 这里还应该把本地的消息附件删除
    ICMessageFrame * messageF = [self.dataSource objectAtIndex:_longIndexPath.row];
    [self statusChanged:messageF];
}

- (void)recallMessage:(UIMenuItem *)recallMenuItem
{
    // 这里应该发送消息撤回的网络请求
    ICMessageFrame * messageF = [self.dataSource objectAtIndex:_longIndexPath.row];
    [self.dataSource removeObject:messageF];
    
    ICMessageFrame *msgF = [ICMessageHelper createMessageFrame:TypeSystem content:@"你撤回了一条消息" path:nil from:@"gxz" to:self.group.gId fileKey:nil isSender:YES receivedSenderByYourself:NO];
    [self.dataSource insertObject:msgF atIndex:_longIndexPath.row];
    [self.tableView reloadData];
}


- (void)statusChanged:(ICMessageFrame *)messageF
{
    [self.dataSource removeObject:messageF];
    [self.tableView beginUpdates];
    [self.tableView deleteRowsAtIndexPaths:@[_longIndexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView endUpdates];
}

- (void)forwardMessage:(UIMenuItem *)forwardItem
{
    ICLog(@"需要用到的数据库，等添加了数据库再做转发...");
}

#pragma mark - Getter and Setter

- (ICChatBoxViewController *) chatBoxVC
{
    if (_chatBoxVC == nil) {
        _chatBoxVC = [[ICChatBoxViewController alloc] init];
        [_chatBoxVC.view setFrame:CGRectMake(0,APP_Frame_Height-HEIGHT_TABBAR, App_Frame_Width, APP_Frame_Height)];
        _chatBoxVC.delegate = self;
    }
    return _chatBoxVC;
}

-(UITableView *)tableView
{
    if (nil == _tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
//        _tableView.contentInset = UIEdgeInsetsMake(-(HEIGHT_STATUSBAR+HEIGHT_NAVBAR), 0, 0, 0);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (NSMutableArray *)dataSource
{
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (UIImageView *)presentImageView
{
    if (!_presentImageView) {
        _presentImageView = [[UIImageView alloc] init];
    }
    return _presentImageView;
}

- (ICVoiceHud *)voiceHud
{
    if (!_voiceHud) {
        _voiceHud = [[ICVoiceHud alloc] initWithFrame:CGRectMake(0, 0, 155, 155)];
        _voiceHud.hidden = YES;
        [self.view addSubview:_voiceHud];
        _voiceHud.center = CGPointMake(App_Frame_Width/2, APP_Frame_Height/2);
    }
    return _voiceHud;
}

- (NSTimer *)timer
{
    if (!_timer) {
        _timer =[NSTimer scheduledTimerWithTimeInterval:0.3f target:self selector:@selector(progressChange) userInfo:nil repeats:YES];
    }
    return _timer;
}
#pragma mark --网络接口方法
- (void)getVisitorName
{
//    self.request=[[HttpRequest alloc] init];
    self.urlHead=@"http://172.16.1.174";
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/getVisitorUsername",_urlHead];
    NSLog(@"url:%@",urlStr);
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"getVisitorUsername",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@ "msgBody":[NSNull null]};
    NSString *paramStr=[paramDic jsonString];
    NSLog(@"%@\n%@",paramDic,paramStr);
    [self.request post:urlStr params:paramStr finish:^(NSString *info) {
         NSLog(@"访客生产一个用户名:%@",info);
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0) {
            self.username=returnDic[@"resultData"][@"username"];
            NSLog(@"username:%@",self.username);
            [[NSUserDefaults standardUserDefaults] setObject:_username forKey:@"username"];
            [[NSUserDefaults standardUserDefaults] synchronize];
             [self visitorLogin];
          
        }
        NSLog(@"返回结果:%@",returnDic);
    } failure:^(NSError *error) {
        NSLog(@"错误描述:%@",error.localizedDescription);
    }];
    
}
- (void)visitorLogin
{
//    self.urlHead=@"http://172.16.1.174";
//    NSString *urlStr=[NSString stringWithFormat:@"%@/service/visitorLogin",_urlHead];
//    NSLog(@"url:%@",urlStr);
//    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"visitorLogin",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"username":_username}};
//    NSString *paramStr=[paramDic jsonString];
//    NSLog(@"%@\n%@",paramDic,paramStr);
//    [self.request post:urlStr params:paramStr finish:^(NSString *info) {
//        NSLog(@"使用访客用户名登录系统:%@",info);
//        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
//        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//        if ([returnDic[@"response"][@"resultCode"] intValue]==0)
//        {
//            self.token=returnDic[@"resultData"][@"token"];
//            self.userId=returnDic[@"resultData"][@"userId"];
//            NSLog(@"token:%@\n userId:%@",self.token,self.userId);
//            [[NSUserDefaults standardUserDefaults] setObject:_username forKey:@"token"];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//            [[NSUserDefaults standardUserDefaults] setObject:_username forKey:@"userId"];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//            NSLog(@"登录结果:%@",returnDic);
//            [self createSocket];  //连接websocket
//            [self createSession];
//        }
//
//    } failure:^(NSError *error) {
//        NSLog(@"登录错误描述:%@",error.localizedDescription);
//    }];
   
    [[YiChatClient shareInstance] visitorLogin:_username Success:^(NSString *info) {
        
        NSLog(@"使用访客用户名登录系统:%@",info);
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0)
        {
            self.token=returnDic[@"resultData"][@"token"];
            self.userId=returnDic[@"resultData"][@"userId"];
            
            NSLog(@"token:%@\n userId:%@",_token,_userId);
            [[NSUserDefaults standardUserDefaults] setObject:_token forKey:@"token"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[NSUserDefaults standardUserDefaults] setObject:_userId forKey:@"userId"];
            [[NSUserDefaults standardUserDefaults] synchronize];
//            NSLog(@"登录结果:%@",returnDic);
            [self createSocket];  //连接websocket
            NSDictionary *calldata=@{@"f1":@"15692450911",@"f2":@"v2"};
            [[YiChatClient shareInstance] createSessionSkillId:@"4" Level:1 callData:calldata Success:^(NSString *info) {
                NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
               
                if ([returnDic[@"response"][@"resultCode"] intValue]==0)
                {
                    self.sessionId=returnDic[@"resultData"][@"sessionId"];
                    NSLog(@"vistorLogin self.sessionId:%@", self.sessionId);
                    
                    [[NSUserDefaults standardUserDefaults] setObject:_sessionId forKey:@"sessionId"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }else if ([returnDic[@"response"][@"resultCode"] intValue]==100010)
                {
                    NSLog(@"已经申请过建立会话");
                    self.sessionId=returnDic[@"resultData"][@"sessionId"];
                    [[NSUserDefaults standardUserDefaults] setObject:_sessionId forKey:@"sessionId"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    NSLog(@"sessionId:%@",self.sessionId);
                }
              
                
                [[YiChatClient shareInstance] getLatestSessionSuccess:^(NSString *info) {
                    if(info!=nil)
                    {
                        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
                        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                        NSLog(@"获取最新会话:%@",returnDic);
                        
                    }
                   
                    
                } fail:^(NSError *error) {
                    NSLog(@"获取最新会话报错:%@",error.localizedDescription);
                }];
                
                
            } fail:^(NSError *error) {
                  NSLog(@"创建会话报错:%@",error.localizedDescription);
            }];
//            [[YiChatClient shareInstance] createSessionSuccess:^(NSString *info) {
//                NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
//                NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//                if ([returnDic[@"response"][@"resultCode"] intValue]==0)
//                {
//                    self.sessionId=returnDic[@"resultData"][@"sessionId"];
//                     [[NSUserDefaults standardUserDefaults] setObject:_sessionId forKey:@"sessionId"];
//                    [[NSUserDefaults standardUserDefaults] synchronize];
//                }else if ([returnDic[@"response"][@"resultCode"] intValue]==100010)
//                {
//                    NSLog(@"已经申请过建立会话");
//                    self.sessionId=returnDic[@"resultData"][@"sessionId"];
//                    [[NSUserDefaults standardUserDefaults] setObject:_sessionId forKey:@"sessionId"];
//                    [[NSUserDefaults standardUserDefaults] synchronize];
//                    NSLog(@"sessionId:%@",self.sessionId);
//                }
//
//                [[YiChatClient shareInstance] getLatestSessionSuccess:^(NSString *info) {
//                    if(info==nil)
//                    {
//                        NSLog(@"获取会话返回空");
//                    }
//                    NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
//                    NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//                    NSLog(@"获取最新会话:%@",returnDic);
//
//                } fail:^(NSError *error) {
//                    NSLog(@"获取最新会话报错:%@",error.localizedDescription);
//                }];
//
//
//            } fail:^(NSError *error) {
//                NSLog(@"创建会话报错:%@",error.localizedDescription);
//            }];
        }
        
    } fail:^(NSError *error) {
        NSLog(@"登陆报错:%@",error.localizedDescription);
    }];
    
}
- (void)createSession
{
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/createSession",_urlHead];
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"createSession",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"skillId":@"2",@"level":@(1),@"callData":@{@"f1":@"v1",@"f2":@"v2"}  }};
    NSString *paramStr=[paramDic jsonString];
    
    NSLog(@"创建会话参数:%@",paramDic);

 
//    self.request2=[[HttpRequestWithToken alloc] init];
//    [self.request2.request setValue:_token forHTTPHeaderField:@"Authorization"];
    [self.request2.request addValue:self.token forHTTPHeaderField:@"Authorization"];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        NSLog(@"建立会话:%@",info);
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0)
        {
            self.sessionId=returnDic[@"resultData"][@"sessionId"];
            [[NSUserDefaults standardUserDefaults] setObject:_sessionId forKey:@"sessionId"];
            NSLog(@"sessionId:%@",self.sessionId);
//            [self sendMessage];
        }else if ([returnDic[@"response"][@"resultCode"] intValue]==100009)
        {
            NSLog(@"Token异常");
            [self visitorLogin];
        
        }else if ([returnDic[@"response"][@"resultCode"] intValue]==100010)
        {
            NSLog(@"已经申请过建立会话");
            self.sessionId=returnDic[@"resultData"][@"sessionId"];
            [[NSUserDefaults standardUserDefaults] setObject:_sessionId forKey:@"sessionId"];
            [[NSUserDefaults standardUserDefaults] synchronize];
             NSLog(@"sessionId:%@",self.sessionId);
//            [self dropSession];
//            [self createSession];
//            [CCDemoUtil showAlertWithTitle:@"提示" content:@"sessionId"];
//            [self visitorLogin];
            
        }else if ([returnDic[@"response"][@"resultCode"] intValue]==100011)
        {
            NSLog(@"已经申请过建立会话，系统已自动结束");
        }else if ([returnDic[@"response"][@"resultCode"] intValue]==100006)
        {
            NSLog(@"当前非服务时间");
        }

    } failure:^(NSError *error) {
         NSLog(@"创建会话错误描述:%@",error.localizedDescription);
    }];
}
//- (void)sendMessage:(NSString*)content type:(NSString*)type
//{
//
//}
//- (void)sendMessage:(NSString*)content
- (void)sendMessage:(NSString*)content type:(NSString*)type
{
    if(content==nil||content.length==0)
    {
         NSLog(@"content为空");
        return;
    }
    if(self.sessionId==nil||self.sessionId==0)
    {
        NSLog(@"sessionId为空");
        return;
    }
    if (self.token==nil||self.token.length==0)
    {
         NSLog(@"token为空");
        return;
    }
    self.request2=[[HttpRequestWithToken alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/sendMessage",_urlHead];
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"sendMessage",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"sessionId":self.sessionId,@"content":content,@"type":type}};
    NSString *paramStr=[paramDic jsonString];
//    [self.request2.request addValue:self.token forHTTPHeaderField:@"Authorization"];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        if(info==nil)
        {
            return ;
        }
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0)
        {
            NSLog(@"发送消息结果:%@",returnDic[@"response"][@"resultMsg"]);
        }
        
    } failure:^(NSError *error) {
        NSLog(@"发送消息失败:%@",error.localizedDescription);
    }];
}
- (void)dropSession
{
    self.request2=[[HttpRequestWithToken alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/sendMessage",_urlHead];
    if (self.sessionId==nil||self.sessionId.length==0)
    {
        NSLog(@"sessionid为空");
        return;
    }
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"dropSession",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"sessionId":self.sessionId}};
    NSString *paramStr=[paramDic jsonString];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0)
        {
            NSLog(@"dropSession:%@",returnDic[@"response"][@"resultMsg"]);
        }
        
    } failure:^(NSError *error) {
        
    }];
}
//- (void)uploadFile:(NSData*)data type:(NSString*)fileType
//{
//
//}
//- (void)uploadFile:(UIImage*)image
- (void)uploadFile:(NSData*)data type:(NSString*)fileType
{
    NSLog(@"token:%@",self.token);
     NSString *urlStr=[NSString stringWithFormat:@"%@/service/upload",_urlHead];

    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
//    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
//    NSDictionary *paramdic=@{@"Authorization":self.token};
//    [manager.requestSerializer setValue:self.token forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"];
    manager.responseSerializer.acceptableContentTypes= [NSSet setWithObjects:@"application/json",@"application/form-data",
                                                        @"text/html",
                                                        @"image/jpeg",
                                                        @"image/png",
                                                        @"application/octet-stream",
                                                        @"text/json",@"text/plain",
                                                        nil];
    
    
    [manager POST:urlStr parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *tokenData=[self.token dataUsingEncoding:NSUTF8StringEncoding];
        [formData appendPartWithFormData:tokenData name:@"token"];
        
        
        //        NSData *imageData =UIImageJPEGRepresentation(self.pickedImage,1);
//        NSData *imageData =nil;
//        if (UIImagePNGRepresentation(image)==nil) {
//            imageData = UIImageJPEGRepresentation(image, 1.0);
//        }else{
//            imageData = UIImagePNGRepresentation(image);
//        }
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat =@"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = @"";
        NSString *mimeType=@"";
        if([fileType isEqualToString:@"voice"])
        {
            fileName=[NSString stringWithFormat:@"%@.wav", str];
            mimeType=[NSString stringWithFormat:@"%@/wav",fileType];
        }else  if([fileType isEqualToString:@"image"])
        {
            fileName = [NSString stringWithFormat:@"%@.png", str];
            mimeType=[NSString stringWithFormat:@"%@/png",fileType];
        }
       

        //上传的参数(上传图片，以文件流的格式)
        [formData appendPartWithFileData:data
                                    name:@"file"
                                fileName:fileName
                                mimeType:mimeType];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印下上传进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //上传成功
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"success:%@",dic);
        if ([dic[@"resultCode"] intValue]==0)
        {
            NSString *url=dic[@"resultData"][@"attachment"];
            NSLog(@"url:%@",url);
            NSMutableDictionary *content=[NSMutableDictionary dictionary];
            if([url hasSuffix:@".png"])
            {
                [content setObject:url forKey:@"picUrl"];
                NSString *contentJson=[content jsonString];
                NSLog(@"picUrl:%@",contentJson);
                [self sendMessage:contentJson type:fileType];
            }else if([url hasSuffix:@".wav"])
            {
                [content setObject:@"voice" forKey:@"msgType"];
                [content setObject:url forKey:@"mediaUrl"];
                [content setObject:@"4" forKey:@"mediaLength"];
                NSString *contentJson=[content jsonString];
                NSLog(@"wav:%@",contentJson);
                [self sendMessage:contentJson type:fileType];
            }
            NSLog(@"发送url地址完成");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //上传失败
        NSLog(@"Error:%@",error);
    }];
    
    
}
- (void)transferToAgent
{

    [[YiChatClient shareInstance] transferToAgent];
    [[YiChatClient shareInstance] getQueueInfoSuccess:^(NSString *info) {
        NSLog(@"获取排队人数:%@",info);
    } fail:^(NSError *error) {
        NSLog(@"获取排队人数报错:%@",error.localizedDescription);
    }];
    
    
    //[self showWebVideo:@"889861496"];
    
    
//    [[YiChatClient shareInstance] getLatestSessionSuccess:^(NSString *info) {
//       
//        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
//        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//        NSLog(@"获取最新会话:%@",returnDic);
//       
//        
//    } fail:^(NSError *error) {
//        NSLog(@"获取最新会话报错:%@",error.localizedDescription);
//    }];
//    AccountVerifyController *vc=[[AccountVerifyController alloc] init];
//    vc.custAcctType=self.custAcctType;
//    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)deleteLocalDB
{
    [[MessageManager shareInstance] deleteData];
    [self.dataSource removeAllObjects];
    [self loadDataSource];
    [self.tableView reloadData];
}
-(NSData*)imageToData:(UIImage*)image
{
    NSData *imageData=nil;
    if (UIImagePNGRepresentation(image)==nil) {
        imageData = UIImageJPEGRepresentation(image, 1.0);
    }else{
        imageData = UIImagePNGRepresentation(image);
    }
    return imageData;
}
- (UIImage*)getFile:(NSString*)url
{
    self.request=[[HttpRequest alloc] init];
//     __block  UIImage *image=nil;
     UIImage *image=nil;
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/getFile?filePath=%@",_urlHead,url];
    NSLog(@"下载图片的地址:%@",urlStr);
    NSURL *URL=[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:60];
    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    image=[UIImage imageWithData:received];
     NSLog(@"下载图片完成");
    return [image copy];
}
#pragma  mark  --webSocket
- (void)createSocket
{
    [SocketRocketUtility instance].token=self.token;
//    [SocketRocketUtility instance].serverAddress=@"172.16.1.174:9901";
//    if ([SocketRocketUtility instance].socketReadyState==SR_CLOSED) {
    
//        [[SocketRocketUtility instance] SRWebSocketOpen];
    
//    [[SocketRocketUtility instance] SRWebSocketOpenwithServer:zt_ONLINE_SERVICES_IP_SOCKET token:self.token];
//   [[SocketRocketUtility instance] SRWebSocketOpenwithServer:@"172.16.1.174:443" token:self.token];
    
    NSLog(@"debug self.userId:%@", self.userId);
    
    [[SocketRocketUtility instance] SRWebSocketOpenwithServer:[SocketRocketUtility instance].serverAddress token:self.token userId:self.userId];
    [SocketRocketUtility instance].delegate=self;
//    }
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SRWebSocketDidOpen) name:@"kWebSocketDidOpenNote" object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SRWebSocketDidReceiveMsg:) name:@"kWebSocketdidReceiveMessageNote" object:nil];
}
- (void)SRWebSocketDidOpen {
    NSLog(@"开启成功");
    //在成功后需要做的操作。。。

    
}

- (void)SRWebSocketDidReceiveMsg:(NSNotification *)note {
    //收到服务端发送过来的消息
    NSString * message = note.object;
    NSData *data=[message dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *receiveDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    
//    NSLog(@"来自服务端收到的消息:%@",receiveDic);
//    [self messageDisplay:receiveDic];
//    [self otherSendTextMessageWithContent:message];
}

- (void)receiveServerMessage:(NSDictionary*)message
{
    
    NSLog(@"xxx receiveServerMessage:%@", message);
    if([message[@"response"][@"msgType"] isEqualToString:@"CHAT_SESSION_DISCONNECTED"])
    {
        self.IsCustermerOnline=NO;
        [self sendSystemMessage:@"会话断开"];
        [[YiChatClient shareInstance] evaluationRobotAccesssId:@"1" Level:1 Content:@"服务不满意" Success:^(NSString *info) {
            NSLog(@"评价机器人:%@",info);
        } fail:^(NSError *error) {
            
        }];
    }else if ([message[@"response"][@"msgType"] isEqualToString:@"CHAT_SESSION_RECEIVEDATA"])
    {
        NSLog(@"消息类型:%@",message[@"resultData"][@"type"]);
        if([message[@"resultData"][@"type"] isEqualToString:@"image"])
        {
//            NSString *imgUrl=message[@"resultData"][@"content"][@"picUrl"];
            NSString *content=message[@"resultData"][@"content"];
            NSData *data=[content dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *contentdic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSString *imgUrl=contentdic[@"picUrl"];
//            NSLog(@"图片地址:%@",imgUrl);
//            UIImage  *image=[self getFile:imgUrl];
//            __block UIImage *image=nil;
//            [[YiChatClient shareInstance] getFile:imgUrl Success:^(NSData *data) {
//                image=[UIImage imageWithData:data];
//            } fail:^(NSError *error) {
//                NSLog(@"下载图片报错:%@",error.localizedDescription);
//            }];
             NSData *imageData=[[YiChatClient shareInstance] getFile:imgUrl];
            UIImage  *image=[UIImage imageWithData:imageData];
            NSString *imagePath=[[ICMediaManager sharedManager] saveImage:image];
//            [self sendImageMessageWithImgPath:imagePthe];
             NSString  *from= message[@"resultData"][@"msgFrom"];
            self.msgFrom=from;
            if(image&&imagePath)
            {
                if (![self.userId isEqualToString:self.msgFrom])
                {
                    [self otherSendImageMessageWithImgPath:imagePath];
                }
               
            }
        }else if ([message[@"resultData"][@"type"] isEqualToString:@"text"])
        {
            NSString  *from= message[@"resultData"][@"msgFrom"];
            NSString *content= message[@"resultData"][@"content"];
            NSMutableString *wholeContent=[NSMutableString stringWithFormat:@"%@\n",content];
            
            NSMutableString *relatedQuestion= [NSMutableString stringWithFormat:@"%@",message[@"resultData"][@"relatedQuestion"]];
            if(message[@"resultData"][@"relatedQuestion"]==nil)
            {
                relatedQuestion=nil;
            }
//            [relatedQuestion deleteCharactersInRange:NSMakeRange(0, 1)];
//            [relatedQuestion deleteCharactersInRange:NSMakeRange(relatedQuestion.length-1, 1)];
//            NSLog(@"relatedQuestion:%@",relatedQuestion);
            if(![NSString isNilString:relatedQuestion])// ![relatedQuestion isEqualToString:@"[]"]||
            {
                [wholeContent appendFormat:@"%@",@"您可以这样问:\n"];
                NSData *data=[relatedQuestion dataUsingEncoding:NSUTF8StringEncoding];
                NSArray *relatedQuestionAry=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                NSLog(@"relatedQuestionAry:%@",relatedQuestionAry);
                for (NSDictionary *dic in relatedQuestionAry)
                {
                    NSLog(@"有关问题:%@",dic[@"content"]);
                    NSString *str=dic[@"content"];
                    [wholeContent appendFormat:@"%@\n",str];
                    
                }
                
            }
            self.msgFrom=from;
            if (![self.userId isEqualToString:self.msgFrom])
            {
              [self otherSendTextMessageWithContent:wholeContent msgFrom:from];
            }
            
        }else if ([message[@"resultData"][@"type"] isEqualToString:@"custVerify"])
        {
            NSString *content= message[@"resultData"][@"content"];
            NSData *data=[content dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *contentdic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
             NSString  *from= message[@"resultData"][@"msgFrom"];
             self.msgFrom=from;
            NSString *msg=contentdic[@"content"];
            self.custAcctType=contentdic[@"custAcctType"];
            [YiChatClient shareInstance].custAcctType=contentdic[@"custAcctType"];
//            [self otherSendTextMessageWithContent:message];
            
            if (![self.userId isEqualToString:self.msgFrom])
            {
              [self otherSendVerifyMessage:msg];
            }
        }else if ([message[@"resultData"][@"type"] isEqualToString:@"voice"])
        {
            NSString *content= message[@"resultData"][@"content"];
            NSData *data=[content dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *contentdic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSString *mediaUrl=contentdic[@"mediaUrl"];
            NSLog(@"语音地址:%@",mediaUrl);
            NSData *voiceData=[[YiChatClient shareInstance] getFile:mediaUrl];
          NSString *voicePath=[[ICRecordManager shareManager] recorderPathWithFileName:[NFTool getTimestamp]];
            NSLog(@"voicePath:%@,length:%ld",voicePath,voiceData.length);
//             [ICFileTool createFilePath:voicePath];
            BOOL isSuccess=[voiceData writeToFile:voicePath atomically:YES];
              NSLog(@"isSuccess---%d",isSuccess);

             NSString  *from= message[@"resultData"][@"msgFrom"];
            self.msgFrom=from;
            if (![self.userId isEqualToString:self.msgFrom])
            {
                  [self otherSendVoiceMessage:voicePath];
            }
           
//            [self otherSendTextMessageWithContent:content];
           
        }else if ([message[@"resultData"][@"type"] isEqualToString:@"evaluateRobot"])
        {
             NSString  *from= message[@"resultData"][@"msgFrom"];
             [self otherSendTextMessageWithContent:@"请评价机器人服务" msgFrom:from];
            NSLog(@"评价机器人的服务");
        }else if ([message[@"resultData"][@"type"] isEqualToString:@"evaluate"])
        {
            NSString  *from= message[@"resultData"][@"msgFrom"];
            NSString  *transferId=message[@"resultData"][@"content"];
            NSLog(@"transferId:%@",transferId);
            [YiChatClient shareInstance].transferId=transferId;
            [self otherSendTextMessageWithContent:@"#请评价座席的服务" msgFrom:from];
            [[YiChatClient shareInstance] getEvaluationOptionsSuccess:^(NSString *info) {
                
               NSArray *evaluationConfigAry= message[@"resultData"][@"evaluationConfig"];
              NSLog(@"获取评价选项结果:%@,%@",info,evaluationConfigAry);
                
                
//                int level=2;
//                NSString *evaluateContent=@"服务很好";
//                [[YiChatClient shareInstance] evalutionLevel:level Content:evaluateContent Success:^(NSString *info) {
//                    NSLog(@"评价成功结果:%@",info);
//                } fail:^(NSError *error) {
//                     NSLog(@"评价失败结果:%@",error.localizedDescription);
//                }];
//                [[YiChatClient shareInstance] evalutionTransferId:transferId Level:level Content:evaluateContent Success:^(NSString *info) {
//                      NSLog(@"评价成功结果:%@",info);
//                } fail:^(NSError *error) {
//                     NSLog(@"评价失败结果:%@",error.localizedDescription);
//                }];
                
            } fail:^(NSError *error) {
                NSLog(@"获取评价选项:%@",error.localizedDescription);
            }];
            NSLog(@"评价座席的服务");
        }else if ([message[@"resultData"][@"type"] isEqualToString:@"imageText"])
        {
            NSLog(@"图文消息:%@",message);
            NSString  *from= message[@"resultData"][@"msgFrom"];
            self.msgFrom=from;
            NSString *content= message[@"resultData"][@"content"];
            NSMutableString *wholeContent=[NSMutableString stringWithFormat:@"%@\n",content];
            
            NSMutableString *relatedQuestion= [NSMutableString stringWithFormat:@"%@",message[@"resultData"][@"relatedQuestion"]];
            
            NSLog(@"relatedQuestion:%@",relatedQuestion);
            if(![relatedQuestion isEqualToString:@"[]"])
            {
                [wholeContent appendFormat:@"%@",@"您可能想问的问题:\n"];
                NSData *data=[relatedQuestion dataUsingEncoding:NSUTF8StringEncoding];
                NSArray *relatedQuestionAry=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                NSLog(@"relatedQuestionAry:%@",relatedQuestionAry);
                for (NSDictionary *dic in relatedQuestionAry)
                {
                    NSLog(@"有关问题:%@",dic[@"content"]);
                    NSString *str=dic[@"content"];
                    [wholeContent appendFormat:@"%@\n",str];
                    
                }
                
            }
            self.msgFrom=from;
            if (![self.userId isEqualToString:self.msgFrom])
            {
                [self otherSendTextMessageWithContent:wholeContent msgFrom:from];
            }
        }else if([message[@"resultData"][@"type"] isEqualToString:@"busicode"])
        {
            NSDictionary *dic=@{@"brand":@"101",@"channelId":@(27),@"size":@(4),@"type":@"text",@"mode":@(1)};
            [[YiChatClient shareInstance] getHotQuestions:dic Success:^(NSString *info) {
                NSLog(@"获取热点问题:%@",info);
            }];
//            [[YiChatClient shareInstance] continueBusi:@"501" validateInfo:@"1ebe6fa5e234127021a91efcb38c408f094b9ab6299d87355c08413c5f5200f44a94220bd30047df" Success:^(NSString *info) {
//                NSLog(@"继续业务办理:%@",info);
//            }];
        }else if ([message[@"resultData"][@"type"] isEqualToString:@"order"]){
            NSString* contentStr = message[@"resultData"][@"content"];
            NSDictionary* contentDict = [NSDictionary dictionaryWithJsonString:contentStr];
            if([contentDict[@"type"] isEqualToString:@"meeting"]){
                NSString* roomId = contentDict[@"roomId"];
                NSLog(@"房间指令:%@", roomId);
                if(self.videoVc==nil){
                    [self showWebVideo:roomId];
                }
                
            }

        }
        
        
        
    }else if([message[@"response"][@"msgType"] isEqualToString:@"CHAT_SESSION_ROBOT_CONNECTED"])
    {
        [self sendSystemMessage:@"与机器人会话建立"];
    }else if([message[@"response"][@"msgType"] isEqualToString:@"CHAT_SESSION_QUEUING"])
    {
        [self sendSystemMessage:@"正在排队等待座席"];
    }else if([message[@"response"][@"msgType"] isEqualToString:@"CHAT_SESSION_QUEUE_TIMEOUT"])
    {
        [self sendSystemMessage:@"排队超时"];
    }else if([message[@"response"][@"msgType"] isEqualToString:@"CHAT_SESSION_CONNECTED"])
    {
        ;
        NSString *agentNiceName=message[@"resultData"][@"agentNiceName"];
        if(![NSString isNilString:agentNiceName])
        {
            NSLog(@"会话建立,座席:%@",agentNiceName);
            self.IsCustermerOnline=YES;
        }
    }
}
- (NSString*)getRecipt:(NSString*)notifyId
{
    NSDictionary *receipt=@{
                            @"request": @{
                                    @"version": @"1.0",
                                    @"msgType": @"receipt",
                                    @"sequenceNo": @(1513734318729)
                                    },
                            @"msgBody": @{
                                    @"notifyId": notifyId
                                    }
                            
                            };
    NSString *receiptStr=[receipt jsonString];
    return receiptStr;
}
- (BOOL)findNotifyId:(NSString*)notifyId InAry:(NSMutableArray*)notifyAry
{
    int  notifyIdCount=0;
    if ([notifyAry count]==1) {
//        NSLog(@"数组只有一个元素");
        return NO;
    }
    for (int i=0;i<notifyAry.count;i++)
    {
//        NSLog(@"遍历数组");
        NSDictionary *dic=[notifyAry objectAtIndex:i];
        if([[[dic allKeys] firstObject] isEqualToString:notifyId])
        {
            notifyIdCount++;
//             return YES;
        }
       
    }
    if(notifyIdCount>1)
    {
        return YES;
    }
    return NO;
}


-(void)videoClosePressed{
    [_videoVc dismissViewControllerAnimated:YES completion:nil];
    _videoVc = nil;
}


-(void)showWebVideo:(NSString*) roomId{
    
    
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.allowsInlineMediaPlayback = YES;
    WKWebView* webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
    
    _videoVc = [[UIViewController alloc] init];
    [_videoVc.view addSubview:webView];
    
    [webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.right.mas_equalTo(0);
    }];
    
    UIButton* closeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
    [_videoVc.view addSubview:closeBtn];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(50);
        make.left.mas_equalTo(20);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(40);
    }];
    [closeBtn addTarget:self action:@selector(videoClosePressed) forControlEvents:UIControlEventTouchUpInside];
    
    _videoVc.modalPresentationStyle = UIModalPresentationFullScreen;
    
    [self presentViewController:_videoVc animated:YES completion:^{
        
    }];
    
    
    NSString* urlString = [NSString stringWithFormat:@"https://meeting.houmong.com/%@",roomId];
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
    
    [webView loadRequest:request];
}

@end
